package com.ccteam.shared.domain.album

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.fluidmusic.fluidmusic.common.utils.MediaIDHelper
import com.ccteam.shared.api.AlbumDataSource
import com.ccteam.shared.data.album.AlbumListPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.album.AlbumListItem
import com.ccteam.shared.utils.ALBUM_QUALITY
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/2/17
 *
 * 专辑列表Domain层
 * 负责将仓库层 [AlbumRepository] 的内容转换为分页库类型 [PagingData<AlbumListItem>] 类型
 */
class AlbumListDataUseCase @Inject constructor(
    private val mediaIDHelper: MediaIDHelper,
    private val albumDataSource: AlbumDataSource
): PagingUseCase<Any, AlbumListItem>(
    Dispatchers.IO
) {
    override fun execute(parameters: Any): Flow<PagingData<AlbumListItem>> {
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            AlbumListPagingSource(albumDataSource)
        }.flow.map { pagingData ->
            // 将数据转换为 AlbumListItem，它的MediaId为 __FM_ONLINE_ALBUM__/albumId
            pagingData.map {
                AlbumListItem(
                    mediaIDHelper.createMediaId(MediaIDHelper.ONLINE_MEDIA_ALBUM,it.id),
                    it.name,it.imgUrl + ALBUM_QUALITY,it.artistName,it.artistName,it.id)
            }
        }
    }
}